<template>
  <div class="app-container calendar-list-container">

    <!-- filter 条件查询 -->
    <div class="filter-container">

        <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.nickName" style="width: 200px;margin-right:15px;" class="filter-item" placeholder="昵称" >
      </el-input>
      <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.userPhone" style="width: 200px;margin-right:15px;" class="filter-item" placeholder="手机号" >
      </el-input>
      
       <el-input
          clearable
          @keyup.enter.native="handleFilter"
          v-model="listQuery.cardNoExternal"
 style="width: 200px;margin-right:15px;"          class="filter-item"
          maxlength="20"
          placeholder="请输入标识码"
        />
 <el-input
          clearable
          @keyup.enter.native="handleFilter"
          v-model="listQuery.cardNo"
 style="width: 200px;margin-right:15px;"          class="filter-item"
          maxlength="20"
          placeholder="请输入编号"
        />
 <el-input
          clearable
          @keyup.enter.native="handleFilter"
          v-model="listQuery.address"
 style="width: 200px;margin-right:15px;"          class="filter-item"
          maxlength="20"
          placeholder="使用城市"
        />
        <el-select
          clearable
          v-model="listQuery.isFlag"
          filterable
       style="width: 200px;margin-right:15px;"  
          class="filter-item"
          placeholder="请选择状态"
        >
          <el-option
            v-for="item in isFlagOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>


      <el-button class="filter-item"       
 type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
       <el-button
        class="filter-item"
        type="primary"
        @click="handleDownload"
        icon="el-icon-download"
        :loading="downloadLoading"
      >导出</el-button>
            <br/>

           <el-button
          class="filter-item"
          type="primary"
          v-waves
          icon="el-icon-circle-plus-outline"
          @click="beforOpenDialog(1)"
          style="width: 200px;margin-right:15px;margin-top:2px"
        >新增IC卡</el-button>
    </div>

    <!-- table 表格 -->
    <el-table  :data="list" v-loading="loading.list" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column  label="序号" prop='index' align="center" width="80px"/>
      <el-table-column label="昵称" prop="nickName" align="center"/>
      <el-table-column label="手机号" prop="userPhone" align="center"/>
      <el-table-column  label="标识码" prop='cardNoExternal' align="center"/>
      <el-table-column  label="编号" prop='cardNo' align="center"/>
      <el-table-column  label="使用城市" prop='address' align="center"/>
      <el-table-column label="金额(元)" prop="amountInfo" align="center"/>
      <el-table-column label="赠送金额(元)" prop="givenAmountInfo" align="center" />
      <el-table-column label="状态" prop="isFlagInfo" align="center"/>
      <el-table-column label="创建时间" prop="ctime" align="center"/>
      <el-table-column  label="操作"   align="center">
      <template slot-scope="scope" style="width:200px">

          <el-button
            size="mini"
            style="margin-top:5px"
            type="primary"
            v-if="scope.row.isFlag == 2"
            @click="updateIsFlag(scope.row.cardId,1)"
          >启用</el-button>

          <el-button
            size="mini"
            style="margin-top:5px"
            type="warning"
            v-else
            @click="updateIsFlag(scope.row.cardId,2)"
          >禁用</el-button>
             <el-button
            type="danger"
            size="mini"
               v-if="scope.row.userId"
            style="margin-top:5px"
            @click="unbindingIcCard(scope.row.cardId)"
          >解绑</el-button>
                </template>
      </el-table-column>
    </el-table>

    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination 
      background 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="listQuery.offset" 
      :page-sizes="[10, 20, 30, 40,100,300,500]"
      :page-size="listQuery.limit" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total">
      </el-pagination>
    </div>


       <!-- 添加IC卡弹窗 -->
    <el-dialog :title="diglogTitle"  :visible.sync="dialog.add">
      <el-form
        :model="addQuery"
        :rules="bindRules"
        ref="ruleForm"
        label-position="right"
        label-width="120px"
        style="textalign:center"
      >

      
       <el-form-item label="标识码" prop="cardNoExternal">
          <el-input    clearable v-model="addQuery.cardNoExternal" maxlength="30" placeholder="请输入标识码,长度在1~30之间，只能包含字母,数字"></el-input>
        </el-form-item>

      <el-form-item label="编号" prop="cardNo">
          <el-input    clearable v-model="addQuery.cardNo" maxlength="30" placeholder="请输入编号,长度在1~30之间，只能包含字母,数字"></el-input>
        </el-form-item>

        <el-form-item  label="使用城市" required >
        <el-form-item  prop="province" style="display:inline-block">
          <el-select
            clearable
            style="width: 200px;"
            v-model="addQuery.province"
            placeholder="省"
            class="filter-item"
            @change="getCities2(2)"
          >
            <el-option v-for="p in provices" :label="p.NAME" :value="p.AREA_ID" :key="p.AREA_ID"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="city" style="display:inline-block">
          <el-select
            clearable
            style="width: 200px;"
            v-model="addQuery.city"
            placeholder="市"
            class="filter-item"
            @change="getAreas2(2)"
          >
            <el-option v-for="c in cities" :label="c.NAME" :value="c.AREA_ID" :key="c.AREA_ID"/>
          </el-select>
         </el-form-item>
     </el-form-item>
     <el-form-item label="赠送金额(元)" prop="givenAmount">
          <el-input    clearable v-model="addQuery.givenAmount" placeholder="非必填项，请输入赠送金额(元)  大于0的两位小数"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.add = false">取消</el-button>
        <el-button type="primary" :loading="loading.add" @click="add">确定</el-button>
      </div>
    </el-dialog>
   
  </div>
</template>
<script>
import { 
  getAddressByAreaId, 
  getId, 
  getAddress,
  getObjByName,
  getObjByAreaId,
  getByNameProvinceId,
  getByNameCityId,
  getByNameAreaId
} from "@/utils/getAddress";
import { getIcCardTypeList,addIcCard,updateIsFlag,unbindingIcCard} from '@/api/icCard'
import { validatePhone } from '@/utils/validate'
import BackToTop from "@/components/BackToTop";
import VePie from "v-charts/lib/pie";
import { parseTime } from '@/utils'
export default {
  name: 'cardType_list',
   components: {
    BackToTop,
    VePie,
  },

  data() {

    
      var validateCardNoExternal= (rule, value, callback) => {
        if (!value) {
            return callback(new Error('标识码不能为空!'));      
        }
        setTimeout(() => {
          var isNum=/^[A-Za-z0-9]\w{0,29}$/;
          if (!isNum.test(value)) {
            callback(new Error('请输入正确标识码,长度在1~30之间，只能包含字母,数字'));
          } else {
        
          callback();
          }
        }, 300);
      };
  var validateCardNo = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('编号不能为空!'));      
        }
        setTimeout(() => {
          var isNum=/^[A-Za-z0-9]\w{0,29}$/;
          if (!isNum.test(value)) {
            callback(new Error('请输入正确编号,长度在1~30之间，只能包含字母,数字'));
          } else {
        
          callback();
          }
        }, 300);
      };
  var validateAmount = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('金额不能为空!'));      
        }
        setTimeout(() => {
        var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
          if (!isNum.test(value)) {
            callback(new Error('请输入正确金额,金额不能小于0，两位小数以内!'));
          } else {
          if((value+"").length>12){
              callback(new Error('金额超过范围'));
            }
          callback();
          }
        }, 300);
      };

       var validateGivengivenAmount = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('时长不能为空!'));      
        }
        setTimeout(() => {
          var isNum= /^(1|([1-9]\d*))$/
          if (!isNum.test(value)) {
            callback(new Error('时长大于0的正整数!'));
          } else {
            if((value+"").length>12){
              callback(new Error('时长超过范围'));
            }
              callback();
          }
        }, 300);
      };
    return {
      cityV:false,
      provices: [],
      cities: [],
      areas: [],
      pId: '',
      cId: '',
      total: 0,
      dialogType:'',
      agentType:this.$store.state.user.userInfo.managerType,

      // 搜索框信息
      listQuery: {
        offset: 1,
        limit: 10,
        address:"",
        cardNo:"",
        nickName:'',
        userPhone:''
        // isFlag:1
      },
      addQuery: {
        cardNoExternal:'',
        cardNo:'',
        province: '',
        city: '',
        amount: '',
        givenAmount: '',
      },

      bindRules: {
         cardNo: [{ required: true,validator: validateCardNo, trigger: "blur" }],
         cardNoExternal: [{ required: true,validator: validateCardNoExternal, trigger: "blur" }],
         province: [
          { required: true, message: "请选择省", trigger: "blur" }
        ],
        city: [
          { required: true, message: "请选择市", trigger: "blur" }
        ],

      
        },
   
       // 用户状态
       options1:[
        { 
        value:'1',
        label:'正常'
        },
        {
        value:'2',
        label:'禁用'
        }
      ],
       // 用户类型
       options2:[
          {
        value:'1',
        label:'普通用户'
        },
        { 
        value:'2',
        label:'管理员'
        }
      ],
        //  设备绑定的套餐
      isFlagOptions: [
        { value: 1, label: "启用" },
        { value: 2, label: "禁用" },
  
      ],
      // 接收的用户列表数据
      list: null,
      // 控制加载动画
      loading: {
        list: false,
        add: false
      },

      dialog:{
        add:false,
        view:false
      },

      downloadLoading: false
    }
  },
  methods: {
   
    //获取IC卡列表
    async getIcCardList(){
      this.loading.list = true 
    
      try {
         //调用服务器接口
        const { data } = await getIcCardTypeList(this.listQuery)
     
        this.list = data.records.map((item, index) => ({
          index: index + 1,
          cardNo:item.cardNo,
          address:item.province+ item.city,
          amountInfo:item.amount/100,
          givenAmountInfo:item.givenAmount/100,
          isFlagInfo:item.isFlag==1?"启用":"禁用",
           ...item}))
        this.total = data.total
      } catch (error) {
        
      }
      this.loading.list = false     
     },
    //导出
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          "昵称",
          "手机号",
           "标识码",
          "编号",
          "使用城市",
          "金额(元)",
          "赠送金额(元)",
          "状态",
          "创建时间",
        ];
        const filterVal = [
          "nickName",
          "userPhone",
          "cardNoExternal",
          "cardNo",
          "address",
          "amountInfo",
          "givenAmount",
          "isFlagInfo",
          "ctime"
        ];
       const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "IC卡列表"
        });
        this.downloadLoading = false;
      });
    },

  // 数据筛选
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
          return v[j]
      }))
    },



 resetForm(flag) {
      this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
      if (flag) {
        this.addQuery = {
          cardNo: "",
        };
      }
    },
      //添加IC卡
    async add() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          try {
       if(this.addQuery.givenAmount!=''){
           var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
          if (!isNum.test(this.addQuery.givenAmount)) {
             this.$message({
                  type: "error",
                  message: "请输入正确金额,金额大于或等于0，两位小数以内!",
                });
          return
          } else {
           if((this.addQuery.givenAmount+"").length>12){
              this.$message({
                  type: "error",
                  message: "金额超过范围 12位!",
                });
                return
            }
          }
          }else{
            this.addQuery.givenAmount=0;
           }

    let query = {
            cardNoExternal:this.addQuery.cardNoExternal,
            cardNo:this.addQuery.cardNo,
            province: getAddress(this.addQuery.province),
            city: getAddress(this.addQuery.city),
            givenAmount:this.addQuery.givenAmount*100
          };


            this.loading.add = true;
            //调用服务器接口
         const { data } = await addIcCard(query);
      
            this.$message({
              type: "success",
              message: "添加IC卡成功"
            });
            this.dialog.add = false;
            this.loading.add = false;
            this.resetForm();
            this.listQuery.city=''
             this.listQuery.province=''
            this.getIcCardList();
          } catch (error) {
            this.loading.add = false;
           this.resetForm();
          }
        }
      });
    },
    // 
 beforOpenDialog(type, item) {
      if (type === 1) {
        // 新增
        this.resetForm();
      //  this.getCities2(1)
       } 
      //  else {
      //   //  修改
      //   this.resetForm();
      //   const { cardNo,province,city ,givenAmount,amount} = item;
      //   this.addQuery = { ...this.addQuery,cardNo, province,city ,givenAmount,amount };
      //   this.addQuery.amount= this.addQuery.amount/100;
      //   this.addQuery.province = getByNameProvinceId(province);
      //   this.addQuery.city = getByNameCityId(province,city);
      //    this.getCities2();
      //   this.getAreas2();
      // }
      this.dialogType = type;
      this.dialog.add = true;
    },

  unbindingIcCard(cardId) {
      let type="解绑";
  
      this.$confirm(`确定${type}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //调用服务器接口
          const { data } = await unbindingIcCard({
            cardId: cardId,
          });
          this.$message({
            type: "success",
            message: `${type}成功!`,
          });
          this.getIcCardList();
        })
        .catch(() => {});
    },
    
     //禁用启用
    updateIsFlag(cardId, status) {
      let type;
      if (status) {
        type = status == 1 ? "启用" : "禁用";
      } else {
        type = "启用";
      }
      this.$confirm(`确定${type}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //调用服务器接口
          const { data } = await updateIsFlag({
            cardId: cardId,
            isFlag: status,
          });
          this.$message({
            type: "success",
            message: `${type}成功!`,
          });
          this.getIcCardList();
        })
        .catch(() => {});
    },
    
    //搜索
    handleFilter() {
      this.listQuery.offset = 1
      this.getIcCardList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getIcCardList()
    },
    handleCurrentChange(val) {
      this.listQuery.offset = val
      this.getIcCardList()
    },
    searchCity(){
    this.getIcCardList()
    },
   //根据fid 查询省、市、区  fid = 0 查询所有省；查询市或者地区 fid 传对应的省areaID
    getAddressByAreaId(fid) {
      return getAddressByAreaId(fid);
    },
     // 获取对应市
    getCities2(type) {
      if (type) {
        this.addQuery.city = "";
        this.addQuery.area = "";
   //    this.listQuery.province=getAddressByAreaId(this.pId)
        this.cityV=true
      }
      else if (!this.cityV){
        this.cityV=false
      }
      this.pId = this.addQuery.province;
      this.cities = getAddressByAreaId(this.pId);
    },
    // 获取对应的地区
    getAreas2(type) {
      if (type) {
        this.addQuery.area = "";

      }else{
        this.cityV=false
      }

      this.pId = this.addQuery.city;
      this.areas = getAddressByAreaId(this.pId);
    },
    // 获取对应市Id
    getCities() {
      this.addQuery.area = "";
      this.areas = [];
      this.cities = getAddressByAreaId(this.pId);
    },
    // 获取对应的地区
    getAreas() {
      this.addQuery.area = "";
      this.areas = getAddressByAreaId(this.cId);
    }
  },
  //开启页渲染
   created() {
     (this.provices = getAddressByAreaId(0)), 
     this.getIcCardList();
  },
   computed: {
    diglogTitle() {
      return this.dialogType === 1 ? "新增" : "编辑";
    }
  }
}
</script>
